<?php

/**
 * Created by PhpStorm.
 * User: liu85
 * Date: 2017/10/28
 * Time: 20:40
 */
namespace app\common\utils;
use think\facade\Config;

class RedisQueue{

    private $queue;

    private $redis;

    /**
     * @param $queue
     * @param bool $short_connect default 是否长链接
     */
    public function __construct($queue,$short_connect = false){

        $this->redis = new \Redis();
        $redisConfig = Config::get('REDIS_CONFIG');
        if($short_connect) {
            $this->redis->connect($redisConfig['host'], $redisConfig['port']);
        }else {
            $this->redis->pconnect($redisConfig['host'], $redisConfig['port']);
        }

        if(!empty($redisConfig['password'])){
            $this->redis->auth($redisConfig['password']);
        }
        $this->queue = $queue;

    }

    public function __destruct(){
        $this->redis->close();

    }

    public function close(){
        $this->redis->close();
    }

    public function put($value){
        $value = serialize($value);
        return $this->redis->lPush($this->queue, $value);

    }
    public function putWithoutSerialize($value) {
        return $this->redis->lPush($this->queue, $value);
    }
    /**
     * 批量插入到队列
     * @param $arr 需要插入的数据  数组
     * @return bool
     */
    public function puts($arr){
        if(!is_array($arr)){
            return false;
        }
        $status = true;
        foreach($arr as $v){
            $res = $this->put($v);
            if(!$res){
                $status = false;
            }
        }
        return $status;
    }

    public function rput($value){
        $value = serialize($value);
        return $this->redis->rpush($this->queue, $value);
    }

    public function get($size = 1){

        $value = array();
        for( $i = 0 ; $i < $size ; $i++){
            $v = $this->redis->rPop($this->queue);
            if( $v === false ){
                break;
            }
            $value[] = unserialize($v);
        }

        if( 0 === count($value) ){
            $value = false;
        }elseif( 1 == $size ){
            $value = $value[0];
        }

        return $value;

    }

    public function delete(){
        return $this->redis->del($this->queue);
    }

    public function length(){
        return $this->redis->lLen($this->queue);
    }

    public function exists()
    {
        return $this->redis->exists($this->queue);
    }
}